package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.util.AreaInfo;
import com.atguigu.gmall.user.util.BaiDuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author lan
 * @since 2023-05-04
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户登录
     *1.根据账号(登录名,手机号,邮箱号)查询用户记录
     * 2.将提交密码进行加密(md5)
     * 3.判断密码是否一致
     * 4.验证通过
     * 生成令牌UUID
     * 将用户信息存入Redis  key: uuid val: 用户信息
     * 5.将生成令牌跟用户信息响应给客户端浏览器
     * 
     * @param userInfo
     * @param httpServletRequest
     * @return
     */
    @Override
    public Map login(UserInfo userInfo, HttpServletRequest httpServletRequest) {

        //1.根据账号(登录名,手机号,邮箱号)查询用户记录
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName,userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getEmail,userInfo.getLoginName());
        queryWrapper.or().eq(UserInfo::getPhoneNum,userInfo.getLoginName());
        //2.将提交密码进行加密
        UserInfo loginUser = this.getOne(queryWrapper);
        //3.判断密码是否一致
        String userEnterPwd = DigestUtils.md5DigestAsHex(userInfo.getPasswd().getBytes());
        if (loginUser.getPasswd().equals(userEnterPwd)){
            //4.验证通过
            //4.1生成令牌UUID user:uuid
            String token = UUID.randomUUID().toString().replaceAll("-", "").toString();
            String userKey = RedisConst.USER_KEY_PREFIX+token;
            // 4.2 将用户信息存入Redis  key:uuid val:用户信息
            JSONObject userInfoJsonObj=new JSONObject();
            userInfoJsonObj.put("id",loginUser.getId());
            //todo 通过第三方服务 根据IP获取城市
            //String ipAddress = IpUtil.getIpAddress(httpServletRequest);
            String ipAddress = "221.220.109.97";
            AreaInfo area = BaiDuService.getArea(ipAddress);
            if (area!=null){
                //todo 存储设备唯一标识,需要手机端获取手机硬件信息并提交服务端
                userInfoJsonObj.put("ipCity",area.getCity());
            }
            redisTemplate.opsForValue().set(userKey,userInfoJsonObj,30, TimeUnit.HOURS);
            //5.将生成令牌跟用户信息相应给客户端浏览器
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("nickName",loginUser.getNickName());
            return map;
        }else {
            throw new RuntimeException("用户名密码错误!");
        }
    }

    /**
     * 用户退出登录
     *
     * @param token
     * @return
     */
    @Override
    public void logout(String token) {
        String userKey = RedisConst.USER_KEY_PREFIX+token;
        redisTemplate.delete(userKey);
    }
}
